package cn.ichiva.common.web;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

public class HttpUtils {

    public static String doGet(String url){
        return doGet(url,"utf-8");
    }

    /**
     * 向指定URL发送GET方法的请求
     */
    public static String doGet(String url,String charsetName) {
        HttpURLConnection conn = null;
        try {
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.connect();

            if (conn.getResponseCode() == 200) {
                try (InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "utf-8")){
                    char[] tem = new char[1024];
                    int read = reader.read(tem);
                    StringBuffer buffer = new StringBuffer();
                    while (read != -1){
                        buffer.append(tem,0,read);
                        read = reader.read(tem);
                    }
                    return buffer.toString();
                }
            }
        } catch (Exception e) {} finally {
            try {
                conn.disconnect();
            }catch (Exception e){}
        }

        return null;
    }

    public static String doPost(String httpUrl, String param) {
        return doPost(httpUrl,param,"utf-8");
    }


        /**
         * 向指定 URL 发送POST方法的请求
         * @return 所代表远程资源的响应结果
         */
    public static String doPost(String httpUrl, String param,String charsetName) {

        HttpURLConnection conn = null;

        try {
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/json");

            try (OutputStream os = conn.getOutputStream()){
                os.write(param.getBytes());
            }

            if (conn.getResponseCode() == 200) {
                try (InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "utf-8")){
                    char[] tem = new char[1024];
                    int read = reader.read(tem);
                    StringBuffer buffer = new StringBuffer();
                    while (read != -1){
                        buffer.append(tem,0,read);
                        read = reader.read(tem);
                    }
                    return buffer.toString();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
           try {
               conn.disconnect();
           }catch (Exception e){}
        }
        return null;
    }

    /**
     * 并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params
     * @return
     */
    public static String toParamString(Map<String,Object> params){
        return params.entrySet().stream()
                .map(e -> e.getKey() + '=' + e.getValue())
                .collect(Collectors.joining("&"));
    }
}